const api = require("../../request/api")
const request = require("../../request/request")
const util = require("../../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,
        styledata: {
            "bg_color": "white",
            "color": "#000",
            "leftflag": true,
            // "homeflag": true,
            "name": "分销达人申请"
        },

        // 用户信息
        avatarUrl: defaultAvatarUrl,
        uid: '',
        user_name: '未认证',
        userInfo: {},
        fullUserInfo: {},
        mobile: '',
        isVip: false,

        // 协议勾选
        if_read: false,

        // ts组件对话框的 确认取消按钮
        confirmBtn: { content: '马上充值', variant: 'base' },
        isShowjump: false
    },

    jumpMoblie() {
        console.log(22225);
        wx.navigateTo({
            url: '/distribution/moblie/moblie',
            // url: '/pages/home/home',
            success: (result) => {
                console.log(result);
            },
            fail: (err) => {
                console.log(err);
            },
            complete: () => {

            }
        });
    },

    confirmDialog() {
        this.setData({ isShowjump: false });
        wx.navigateTo({
            url: '/vip/buy_vip?from=/distribution/distributor/distributor',
            success: (result) => {

            },
            fail: () => { },
            complete: () => { }
        });

    },

    closeDialog() {
        this.setData({ isShowjump: false });
        wx.navigateBack({
            delta: 1
        });

    },

    // 协议勾选回调
    selecting(e) {
        this.setData({
            if_read: !this.data.if_read
        })
    },


    // 手机授权按钮的回调
    async getrealtimePhoneNumber(e) {
        // console.log(e.detail.code)  // 拒绝：undefined 同意：code（和login的code不一样）
        // console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）拒绝：fail user deny 同意：ok
        // console.log(e.detail.errno)  // 错误码（失败时返回）一般情况：undefined  使用次数上限：e.detail.errno===1400001

        // 用户同意且未达使用次数上限
        if (e.detail.errno == undefined && e.detail.code) {
            // 成功手机号授权会返回 true
            let phoneflag = await App.setPhone(e.detail.code)
            // 成功后请求用户完整信息
            if (phoneflag) {
                // 成功获取最新完整用户信息
                let fullRes = await App.getMyFullInfo()
                if (fullRes) {
                    util.showLoading("已授权,跳转中")
                    // util.showToast('已授权认证分销员')
                    let timer = setTimeout(() => {
                        util.hideLoading()
                        wx.redirectTo({
                            url: '/distribution/index/index',
                            success: (result) => {

                            },
                            fail: (err) => {
                                console.log(err);

                            },
                            complete: () => { }
                        });

                        clearTimeout(timer)
                    }, 2500);
                    // this.init_data()
                    // this.paying()
                    // console.log('是否有手机号？', this.data.mobile);
                } else {
                    util.showFail('认证失败请重试')
                }
            }
        } else {
            util.showToast('已取消认证')
        }
    },

    // 初始化
    init_data() {
        this.setData({
            uid: App.globalData.uid,
            userInfo: App.globalData.userInfo,
            avatar_url: App.globalData.userInfo?.avatarUrl || defaultAvatarUrl,
            user_name: App.globalData.userInfo?.nickName || '请登录',
            fullUserInfo: App.globalData.fulluserInfo,
            mobile: App.globalData.mobile,
            isVip: App.globalData.isVip
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        if (!App.globalData.uid) {
            let flag = await App.confirmLogin('您需要先登录')
            if (flag) {
                // this.getMyCoupons()
            } else {
                wx.navigateBack({
                    delta: 1
                })
            }
        }
        this.init_data()
    },

    totogive() {
        App.checkSub()
    },

    // 授权用户跳转分销中心页面
    gotoDistribution() {
        // wx.redirectTo({
        //     url: '/distribution/index/index',

        // });

        // App.againShow('DexqZyfXPD_zQ9OjnZec9jBQU9sWFpFholrbWaBPM3s') // 订单状态提醒服务
        // App.againShow('yumQ5iVzxelMnOEiu9wRbxTTy0G8tlTBGIu1S8agNfA')
        this.sendTemplateMsg()

    },

    // 发送模板消息
    async sendTemplateMsg(uid, mobile, appid, secret) {
        // 获取后台接口调用凭证
        const tokenUrl = 'https://api.weixin.qq.com/cgi-bin/token'

        let params = {
            appid,
            secret,
            grant_type: 'client_credential'
        }
        let tokenRes = await request.postall(tokenUrl, params, 'GET')
        console.log(tokenRes);

        // 利用凭证向所有管理员发送模板消息
        // , 'oCUbM5OOsQ0-v3HTpgX9jWEXDZqE'
        let openIdArr = ['oCUbM5D_LyzLdnCF0FYaajZ0ZqFs', 'oCUbM5OOsQ0-v3HTpgX9jWEXDZqE']
        const sendUrl = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${tokenRes.access_token}`

        openIdArr.forEach(async item => {
            let sendParams = {
                "data": {
                    "thing1": {
                        "value": "用户认证分销申请"
                    }, "number2": {
                        "value": "1"
                    },
                    "thing3": {
                        "value": "请尽快审核哦亲"
                    },

                    "time9": {
                        "value": "2023-11-10"
                    }
                },
                "touser": item,
                "template_id": "yumQ5iVzxelMnOEiu9wRbxTTy0G8tlTBGIu1S8agNfA",
                "page": "/distribution/verify/verify?index=0&status=0",
                "miniprogram_state": "developer",
                "lang": "zh_HK"
            }
            let SendRes = await request.postall(sendUrl, sendParams)
            console.log(SendRes);
        });

    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 如果非会员，展示充值弹窗
        let isVip = App.globalData.isVip
        if (!isVip) {
            this.setData({
                isShowjump: true
            })
        }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})